package com.example.work4


import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.widget.*
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment

import com.example.work4.fragment.BlankFragment
import com.example.work4.fragment.ListFragment
import com.example.work4.fragment.LoginFragment
import com.example.work4.fragment.MapFragment
import com.example.work4.po.SSOInfo
import com.example.work4.baiduMapSDK.LocationListener
import com.example.work4.baiduMapSDK.LocationService
import com.example.work4.view.StatusBar
import java.lang.System.exit
import java.util.ArrayList
import kotlin.system.exitProcess


class TestActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)
        checkPermission()
        StatusBar.setStatusBarAsBlue(window)
        toLocation = findViewById(R.id.to_location)
        locationService= (application as DemoApp).locationService
        locationService?.registerListener(mListener)
        locationService?.setLocationOption(locationService!!.defaultLocationClientOption)
        locationService?.start()
        mTabRadioGroup = findViewById(R.id.tabs_rg)
        mTabRadioGroup?.setOnCheckedChangeListener(mOnCheckedChangeListener)
        otherFrame = findViewById(R.id.frame)
        initFragment()
    }

    var otherFrame:FrameLayout?=null

    var toLocation: ImageView? = null

    private var mListener: LocationListener = LocationListener()

    private var locationService: LocationService? = null

    private var mTabRadioGroup: RadioGroup? = null

    var frameArray:Array<String> = arrayOf("map","list","blank")

    var curFrag = "list"

    private val mOnCheckedChangeListener = RadioGroup.OnCheckedChangeListener { group, checkedId ->
        if(SSOInfo.isLogin) {
            if (checkedId == R.id.shareButton) {
                replace("list")
            }
            if (checkedId == R.id.mapButton) {
                replace("map")
            }
            if (checkedId == R.id.mineButton) {
                replace("blank")
            }
        }
    }

    fun toLocation(view: View)
    {
        if (curFrag == "map")
        {
            DataUtil.mapHandler!!.sendEmptyMessage(DataUtil.UPDATE_MAP_MARK_LIST)
        }
        else {
            val intent = Intent(applicationContext, PostMomentActivity::class.java);
            startActivity(intent)
        }
    }

    private fun replace(name:String){
        val fragmentManager = supportFragmentManager
        var fragment:Fragment
        val transaction = fragmentManager.beginTransaction()
        for(tag in frameArray){
            fragment = fragmentManager.findFragmentByTag(tag)!!
            if(tag == name){
                transaction.show(fragment)
                curFrag = tag
                if(curFrag == "map"){
                    toLocation!!.setImageResource(R.drawable.vector_update)
                }else{
                    toLocation!!.setImageResource(R.drawable.vector_add)
                }
            }
            else{
                transaction.hide(fragment)
            }
        }
        transaction.commit()
    }

    private fun initFragment(){
        val fragmentManager = supportFragmentManager
        val transaction = fragmentManager.beginTransaction()
        transaction.add(R.id.frame, MapFragment(),"map")
        transaction.add(R.id.frame, BlankFragment(),"blank")
        transaction.add(R.id.frame, ListFragment(),"list")
        if(!SSOInfo.isLogin) {
            transaction.add(R.id.frame, LoginFragment(), "login")
        }
        transaction.commit()

    }



    override fun onDestroy() {
        super.onDestroy()
        locationService!!.unregisterListener(mListener) //注销掉监听
        locationService!!.stop() //停止定位服务
        MapFragment.isCenter=false
    }

    override fun onPause() {
        super.onPause()
        locationService!!.unregisterListener(mListener) //注销掉监听
        locationService!!.stop() //停止定位服务
        MapFragment.isCenter=false
    }

    override fun onResume() {
        super.onResume()
        locationService!!.registerListener(mListener) //注销掉监听
        locationService!!.start() //恢复定位服务
    }

    private val permissions = arrayOf<String>(
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )
    private val PERMISSIONS_RESULT_CODE = 121 // 自定义

    private var firstPressedTime = 0L;

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        val secondTime = System.currentTimeMillis()
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (secondTime - firstPressedTime < 2000) {
                System.exit(0)
            } else {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show()
                firstPressedTime = System.currentTimeMillis()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    /**
     * 申请权限
     */
    private fun checkPermission() {
        // SDK版本 大于或等于23 动态申请权限
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return
        // 检查 未授权 的 权限
        val pl: MutableList<String> = ArrayList()
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(this, permission)
                != PackageManager.PERMISSION_GRANTED
            ) {
                pl.add(permission)
            }
        }
        // 申请权限
        if (pl.size > 0) {
            ActivityCompat.requestPermissions(this, pl.toTypedArray(), PERMISSIONS_RESULT_CODE)
        }
    }

}

